/**
 * 
 */
package com.autoscript.ui.helper;

import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

/**
 * 序列化工具类 作者:龙色波 日期:2013-10-9
 */
public class SerialHelper {
	/**
	 * 保存为xml
	 * 
	 * @param fileName
	 *            文件名
	 * @param o
	 *            对象
	 * @throws FileNotFoundException
	 * @remark 目前jdk xmlEncoder 不支持并发
	 */
	public static void saveToXml(String fileName, Object o)
			throws FileNotFoundException {
		XMLEncoder e = null;
		try {
			e = new XMLEncoder(new BufferedOutputStream(new FileOutputStream(
					fileName)));
			e.writeObject(o);
		} finally {
			if (e != null) {
				e.close();
			}
		}

	}

	/**
	 * 从xml 读取对象
	 * 
	 * @param fileName
	 * @return
	 * @throws FileNotFoundException
	 * @remark 目前jdk xmldecoder 不支持并发
	 */
	public static Object readFromXml(String fileName)
			throws FileNotFoundException {
		XMLDecoder d = null;
		try {
			d = new XMLDecoder(new BufferedInputStream(new FileInputStream(
					fileName)));
			Object result = d.readObject();

			return result;
		} finally {
			if (d != null) {
				d.close();
			}
		}
	}
}
